<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>用户管理</title>
    <link rel="stylesheet" href="/layui/css/layui.css">
    <script src="/layui/layui.js"></script>
    <script src="/js/jquery-3.3.1.min.js"></script>
</head>
<body>


<!-- ---------------条件查询--------------------------  -->
<form class="layui-form" style="margin-top: 10px;margin-left: 10px">
    登录名：
    <div class="layui-inline">
        <input class="layui-input" name="loginName" placeholder="登录名" autocomplete="off">
    </div>
    创建人：
    <div class="layui-inline">
        <input class="layui-input" name="createBy" placeholder="创建人" autocomplete="off">
    </div>
    修改人：
    <div class="layui-inline">
        <input class="layui-input" name="updateBy" placeholder="修改人" autocomplete="off">
    </div>
    <button class="layui-btn" lay-submit lay-filter="selectConditionFilter" data-type="reload">搜索</button>
    <button class="layui-btn layui-btn-primary" type="reset" id="resetButton">重置</button>
</form>


<!-- ---------------------信息表-------------------------- -->
<table id="user" lay-filter="userTableFilter">
</table>

</body>
<!-- --------------------添加弹窗表格---------------------- -->
<form class="layui-form" action="" id="addUserForm" style="display: none;margin-right: 40px;margin-top: 20px">
    <div class="layui-form-item">
        <label class="layui-form-label">登录名</label>
        <div class="layui-input-block">
            <input type="text" name="loginName"  onblur="checkUserName()" id="loginName" placeholder="请输入登录名" required lay-verify="required"
                   autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">密码</label>
        <div class="layui-input-block">
            <input type="text" name="password" placeholder="请输入密码" required lay-verify="required" autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">真实姓名</label>
        <div class="layui-input-block">
            <input type="text" name="userName" placeholder="请输入真实姓名" required lay-verify="required" autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">邮箱</label>
        <div class="layui-input-block">
            <input type="email" name="email" placeholder="请输入邮箱" required lay-verify="required" autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">手机号</label>
        <div class="layui-input-block">
            <input type="tel" name="phonenumber" placeholder="请输入手机号" required lay-verify="required" autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">部门</label>
        <div class="layui-input-block">
            <select name="deptId" lay-verify="required" lay-search="">
                <option th:each="dept:${deptList}" th:value="${dept.deptId}" th:text="${dept.deptName}"></option>
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">状态</label>
        <div class="layui-input-block">
            <input type="checkbox" checked="" name="status" lay-skin="switch" lay-filter="switchTest" lay-text="正常|失效">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">性别</label>
        <div class="layui-input-block">
            <input type="radio" name="sex" value="0" title="男" checked="">
            <input type="radio" name="sex" value="1" title="女">
        </div>
    </div>
    <input hidden name="createBy" value="陈建">
    <div class="layui-form-item" pane="">
        <label class="layui-form-label">角色</label>
        <div class="layui-input-block" id="addRoleCheckBox" name="roles">

        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit id="addUserButton" lay-filter="addUserFilter">立即提交</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </div>
</form>

<!--===================修改弹窗表格========================-->
<form class="layui-form" action="" id="updateUserForm" lay-filter="updateUserFormFilter"
      style="display: none;margin-right: 40px;margin-top: 20px">
    <!--用户id-->
    <input name="userId" hidden="hidden"/>
    <div class="layui-form-item">
        <label class="layui-form-label">登录名</label>
        <div class="layui-input-block">
            <input type="text" name="loginName" placeholder="请输入登录名" readonly disabled required lay-verify="required"
                   autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">真实姓名</label>
        <div class="layui-input-block">
            <input type="text" name="userName" placeholder="请输入真实姓名" required lay-verify="required" autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">邮箱</label>
        <div class="layui-input-block">
            <input type="email" name="email" placeholder="请输入邮箱" required lay-verify="required" autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">手机号</label>
        <div class="layui-input-block">
            <input type="tel" name="phonenumber" placeholder="请输入手机号" required lay-verify="required" autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">部门</label>
        <div class="layui-input-block">
            <select name="deptId" lay-verify="required" lay-search="">
                <option th:each="dept:${deptList}" th:value="${dept.deptId}" th:text="${dept.deptName}"></option>
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">状态</label>
        <div class="layui-input-block">
            <input type="checkbox" name="status" id="updateStatus" lay-skin="switch" lay-filter="switchTest"
                   lay-text="正常|失效">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">性别</label>
        <div class="layui-input-block">
            <input type="radio" name="sex" value="0" title="男" checked="">
            <input type="radio" name="sex" value="1" title="女">
        </div>
    </div>
    <!-- <input hidden name="updateBy" value="陈建">-->
    <div class="layui-form-item" pane="">
        <label class="layui-form-label">角色</label>
        <div class="layui-input-block" name="roles" id="updateRoleCheckBox">

        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">备注</label>
        <div class="layui-input-inline">
            <input type="text" name="remark" required lay-verify="required" placeholder="请输入备注信息" autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit lay-filter="updateUserFilter">立即提交</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </div>
</form>
<!-- -------------------重置密码弹窗表格---------------------- -->
<form class="layui-form" action="" id="resetPasswordForm" lay-filter="resetPasswordFormFilter"
      style="display: none;margin-right: 40px;margin-top: 20px">
    <!--用户id-->
    <!--隐藏输入框，保存主键-->
    <input type="hidden" name="userId">
    <div class="layui-form-item">
        <label class="layui-form-label">密码</label>
        <div class="layui-input-block">
            <input type="text" name="password" placeholder="请输入密码" required lay-verify="required" autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit lay-filter="resetPasswordFilter">立即提交</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </div>
</form>


<!-- -------------------------头部工具栏按钮-------------------------  -->
<script type="text/html" id="userToolbar">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-xs" lay-event="add">
            <i class="layui-icon layui-icon-add-1"></i>添加
        </button>
        <button class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delSelected">
            <i class="layui-icon layui-icon-delete"></i>删除
        </button>
    </div>
</script>
<!-- ----------------------操作按钮----------------------- -->
<script type="text/html" id="userOperation">
    <button class="layui-btn layui-btn-xs layui-btn-normal" lay-event="resetPassword">重置密码</button>
    <button class="layui-btn layui-btn-xs" lay-event="edit">修改</button>
    <button class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del">删除</button>
</script>
<!--检验用户名重复-->
<script>
    // 校验角色名是否存在
    function checkUserName() {
        loginName = $("#loginName").val();
        if (loginName != "") {
            $.post("/user/checkLoginName", {"loginName": loginName}, function (ret) {
                console.log("ret:"+ret);
                if (ret.code == 0) {
                    //关闭对话框
                    // layer.closeAll();
                    // 恢复按钮状态
                    $('#addUserButton').removeClass("layui-btn-disabled").attr("disabled",false);
                } else {
                    layer.msg(ret.msg, {icon: 5});
                    // 禁用按钮状态
                    $('#addUserButton').addClass("layui-btn-disabled").attr("disabled",true);
                }
            });

        }
    }
</script>

<!-- ---------------------状态按钮----------------------- -->
<script type="text/html" id="userState">
    {{# if (d.status === '0'){}}
    <button class="layui-btn layui-btn-xs" lay-event="state">正常</button>
    {{# }else {}}
    <button class="layui-btn layui-btn-xs layui-btn-danger" lay-event="state">失效</button>
    {{# }}}
</script>
<script>
    layui.use(['table', 'layer', 'jquery', 'form'], function () {
        let table = layui.table;
        let layer = layui.layer;
        let $ = layui.jquery;
        let form = layui.form;
        //第一个实例
        let userTable = table.render({
            elem: '#user'
            , url: '/user/findAll' //数据接口
            , toolbar: '#userToolbar' //开启头部工具栏，并为其绑定左侧模板
            , page: true //开启分页
            , cols: [
                [ //表头
                    {type: 'checkbox', fixed: 'left'}
                    , {field: 'userId', title: '编号', width: 80, sort: true}
                    , {field: 'loginName', title: '登录名', width: 100}
                    , {field: 'userName', title: '真实姓名', width: 120}
                    , {field: 'email', title: '邮箱', width: 160}
                    , {field: 'phonenumber', title: '手机号', width: 160}
                    , {
                    field: 'sex', title: '性别', width: 80, templet: function (d) {
                        if (d.sex === "0") {
                            return '男'
                        } else {
                            return '女'
                        }
                    }
                }
                    , {field: '', title: '状态', width: 80, toolbar: "#userState"}
                    //, {field: 'deptName', title: '部门名称', width: 100}
                    , {
                    field: 'deptName', title: '部门名称', width: 100,
                    templet: function (d) {
                        return d.dept.deptName
                    }
                }
                    , {field: 'createBy', title: '创建人', width: 100}
                    , {field: 'createTime', title: '创建时间', width: 160}
                    , {field: 'updateBy', title: '修改人', width: 100}
                    , {field: 'updateTime', title: '修改时间', width: 160}
                    //添加按钮
                    , {fixed: 'right', align: 'center', title: '操作', width: 220, toolbar: "#userOperation"}
                ]]
        });

        let $deptSelect = $("select[name=deptId]");
        let $roleCheckBox = $("div[name=roles]");
        let options = '';
        let inputs = '';

        //==============填充部门下拉框=========================================
        $.ajax({
            url: "/user/findAllDept",
            type: "GET",
            dataType: "JSON",
            success: function (allDept) {
                console.log(allDept)
                //将数据放到select中
                for (let i = 0; i < allDept.length; i++) {
                    options += '<option value="' + allDept[i].deptId + '">' + allDept[i].deptName + '</option>';
                }
                $deptSelect.html(options)
            }
        })
        //================填充角色复选框==========================================
        $.ajax({
            url: "/user/findAllRole",
            type: "GET",
            dataType: "JSON",
            success: function (allRole) {
                //将数据放到select中
                for (let i = 0; i < allRole.length; i++) {
                    inputs += '<input type="checkbox" name="role" value="' + allRole[i].roleId + '" lay-skin="primary" title="' + allRole[i].roleName + '">'
                }
                $roleCheckBox.html(inputs)
            }
        })
        //========查找==========================
        form.on('submit(selectConditionFilter)', function (data) {
            console.log(data.field)
            //当前容器的全部表单字段，名值对形式：{name: value}
            // 提交表单数据
            $.ajax({
                url: "/user/findAll",
                type: "GET",
                dataType: "JSON",
                data: data.field,
                // contentType:"application/json;charset=UTF-8",
                // data:JSON.stringify(data.field),
                success: function (ret) {
                    if (ret.code == 0) {
                        //刷新表格数据
                        userTable.reload({
                            where: { //设定异步数据接口的额外参数，任意设
                                loginName: data.field.loginName
                                , createBy: data.field.createBy
                                , updateBy: data.field.updateBy
                            },
                            page: {
                                curr: 1
                                //重新从第 1 页开始
                            }
                        });
                        // layer.msg(ret.data.question+ret.msg,{icon: 6});
                    } else {
                        layer.msg(ret.msg, {icon: 5});
                    }
                }
            })
            return false;//阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });

        // ==================获取选中复选框项============================
        function selectCheckeds(name) {
            var checkeds = "";
            console.log(checkeds);
            // 保存用户
            if (name != null) {
                $('input:checkbox[name="' + name + '"]:checked').each(function (i) {
                    if (0 == i) {
                        checkeds = $(this).val();
                        console.log(checkeds);
                    } else {
                        checkeds += ("," + $(this).val());
                        console.log(checkeds);
                    }
                });
                //修改用户
            } else {
                $('.roles_check:checked').each(function (i) {
                    if (0 == i) {
                        checkeds = $(this).val();
                        console.log(checkeds);
                    } else {
                        checkeds += ("," + $(this).val());
                        console.log(checkeds);
                    }
                });
            }
            console.log(checkeds);
            return checkeds;
        }

        //======================重置========================
        $("#resetButton").click(function () {
            userTable.reload({
                where: { //设定异步数据接口的额外参数，任意设
                    loginName: ""
                    , createBy: ""
                    , updateBy: ""
                    //…
                }
                , page: {
                    curr: 1 //重新从第 1 页开始
                }
            });
        })

        //===================头工具栏事件====================
        table.on('toolbar(userTableFilter)', function (obj) {
            let checkStatus = table.checkStatus(obj.config.id)
                , data = checkStatus.data;
            switch (obj.event) {
                //================添加数据=======================
                case 'add':
                    //将表单清空
                    document.getElementById("addUserForm").reset();
                    //将登录名的input颜色变为正常
                    let loginInput = document.getElementById("loginName");
                    loginInput.style = "";
                    let $input = $("input[name=role]");
                    for (let j = 0; j < $input.length; j++) {
                        $input[j].checked = false
                    }
                    //重新渲染表单
                    form.render();
                    layer.open({
                        title: '添加用户',
                        type: 1,
                        area: ['500px', '600px'],
                        content: $("#addUserForm"),//这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
                        end:function () {
                            //关闭时的回调函数
                            $("#addUserForm").hide()
                        }
                    });
                    break;
                //=================删除选择的数据================================
                case 'delSelected':
                    if (data.length == 0) {
                        lay.msg('请选择一行');
                    } else {
                        layer.confirm('真的删除行么', function (index) {
                            let userIds = [];
                            for (let i = 0; i < data.length; i++) {
                                userIds[i] = data[i].userId
                            }
                            $.ajax({
                                url: "/user/delSelected",
                                type: "POST",
                                dataType: "JSON",
                                contentType: "application/json;charset=UTF-8",
                                //data: {userIds: userIds.join(",")},
                                data: JSON.stringify(data),//将js对象转成json串传入到后台
                                success: function (ret) {
                                    if (ret.code == 0) {
                                        //刷新表格数据
                                        userTable.reload({});
                                        layer.msg(ret.msg, {icon: 6});
                                    } else {
                                        layer.msg(ret.msg, {icon: 5});
                                    }
                                }
                            })
                            layer.close(index);
                        })
                    }
                    break;
            }
        });

        //=============addUserForm表单的提交================================
        form.on('submit(addUserFilter)', function (data) {

            var checkeds = selectCheckeds("role");
            //盐值在添加的时候没有用处，所以将角色信息放入到盐值中传入后端
            data.field.salt = checkeds;
            console.log(checkeds);
            console.log(data.field) //当前容器的全部表单字段，名值对形式：{name: value}
            //将状态属性的on转换为0，1
            if (data.field.status === "on") {
                data.field.status = 0;
            } else {
                data.field.status = 1;
            }
            //提交表单数据
            $.ajax({
                url: "/user/insertUser",
                type: "POST",
                dataType: "json",
                data: data.field,
                success: function (ret) {
                    console.log(ret);
                    if (ret.code == 0) {
                        //关闭对话框
                        layer.closeAll();
                        //刷新表格数据
                        userTable.reload({
                            page: {
                                curr: 1 //重新从第 1 页开始
                            }
                        });
                        layer.msg(ret.msg, {icon: 6});
                    } else {
                        layer.msg(ret.msg, {icon: 5});
                    }
                }
            })
            // }
            //将表单清空
            document.getElementById("addUserForm").reset();
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });

        //======================行工具栏事件==================================
        table.on('tool(userTableFilter)', function (obj) {
            let data = obj.data;
            switch (obj.event) {
                //=============行工具栏的重置密码========================
                case 'resetPassword':
                    //将表单清空
                    document.getElementById("resetPasswordForm").reset();
                    form.val('resetPasswordFormFilter', {
                        userId: data.userId
                    });
                    layer.open({
                        title: '修改密码',
                        type: 1,
                        area: ['500px', '180px'],
                        content: $("#resetPasswordForm"),//这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
                    });
                    break;
                //=============行工具栏的修改========================
                case 'edit':
                    //将表单清空
                    document.getElementById("updateUserForm").reset();
                    let $input = $("input[name=role]");
                    for (let j = 0; j < $input.length; j++) {
                        $input[j].checked = false
                    }
                    console.log(data.status);
                    if (data.status == 0) {
                        document.getElementById("updateStatus").checked = true
                    } else {
                        document.getElementById("updateStatus").checked = false
                    }

                    //复选框回显
                    $.ajax({
                        url: "/user/findSelectRole",
                        type: "GET",
                        dataType: "JSON",
                        data: {userId: data.userId},
                        success: function (ret) {
                            console.log(ret);
                            data.role = "";
                            console.log(data);
                            for (let i = 0; i < ret.data.length; i++) {
                                if (ret.data.length<=1) {
                                    data.role += ret.data[i].roleId
                                } else {
                                    data.role += ret.data[i].roleId + ","
                                }
                                for (let j = 0; j < $input.length; j++) {
                                    if ($input[j].value == ret.data[i].roleId) {
                                        $input[j].checked = true;
                                    }
                                }
                            }
                            console.log(data);
                            //重新渲染
                            form.render()
                        }
                    })

                    form.val('updateUserFormFilter', {
                        userId: data.userId
                        , loginName: data.loginName
                        , userName: data.userName
                        , email: data.email
                        , phonenumber: data.phonenumber
                        , deptId: data.deptId
                        , sex: data.sex
                    });
                    form.render()

                    layer.open({
                        title: '修改用户',
                        type: 1,
                        area: ['500px', '550px'],
                        content: $("#updateUserForm"),//这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
                        end:function () {
                            //关闭时的回调函数
                            $("#updateUserForm").hide()
                        }
                    });
                    break;
                //=============行工具栏的删除========================
                case 'del':
                    layer.confirm('真的真的删除行么', function (index) {
                        console.log(data);
                        $.ajax({
                            url: "/user/deleteById",
                            type: "POST",
                            dataType: "json",
                            contentType: "application/json;charset=UTF-8",
                            data: JSON.stringify(data),
                            success: function (ret) {
                                if (ret.code == 0) {
                                    console.log(ret);
                                    //刷新表格数据
                                    userTable.reload({
                                        page: {
                                            curr: 1 //重新从第 1 页开始
                                        }
                                    });
                                    layer.msg(ret.msg, {icon: 6});
                                } else {
                                    layer.msg(ret.msg, {icon: 5});
                                }

                            }
                        })
                        layer.close(index);
                    });
                    break;
            }
        });

        //========================update表单的提交======================================
        form.on('submit(updateUserFilter)', function (data) {
            //var checkeds = selectCheckeds("role");
            let yuan = data.field.role;
            data.field.role = "";
            console.log(yuan);
            console.log( data.field.role );

            //let checkedInput = $('input[name=role]:checked');
            let checkedInput = $("#updateRoleCheckBox").find('input[name=role]:checked');
            //let checkedInput = $("input[name='role']").prop("checked");
            console.log(checkedInput);
            console.log(checkedInput.form);
            for (let i = 0; i < checkedInput.length ; i++) {
                console.log(checkedInput.length);
                if (i === checkedInput.length - 1) {
                    data.field.role += checkedInput[i].value
                } else {
                    data.field.role += checkedInput[i].value + ","
                }
            }
            //if(yuan.length !=0){

           // }
            //data.field.role = data.field.role.substring(yuan.length+1);
            if (data.field.role === "") {
                layer.msg("角色不能为空")
            } else {
                //盐值在添加的时候没有用处，所以将角色信息放入到盐值中传入后端
                data.field.salt = data.field.role;

           // data.field.status = data.field.status ? 0 : 1;
            //var checkeds = selectCheckeds();
            //data.field.salt = checkeds;
                console.log(data.field) //当前容器的全部表单字段，名值对形式：{name: value}
                //将状态属性的on转换为0，1*/
                if (data.field.status === "on") {
                    data.field.status = 0;
                } else {
                    data.field.status = 1;
                }
                //提交表单数据
                $.ajax({
                    url: "/user/updateUser",
                    type: "POST",
                    dataType: "JSON",
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify(data.field),
                    success: function (ret) {
                        console.log(ret);
                        if (ret.code === 0) {
                            //关闭对话框
                            layer.closeAll();
                            //刷新表格数据
                            userTable.reload({});
                            layer.msg(ret.msg, {icon: 6});
                        } else {
                            layer.msg(ret.msg, {icon: 5});
                        }
                    }
                })
            }
                return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
            }
        );

        //===============修改密码表单的提交====================
        form.on('submit(resetPasswordFilter)', function (data) {
            console.log(data.field)
            //提交表单数据
            $.ajax({
                url: "/user/updatePassword",
                type: "PUT",
                dataType: "JSON",
                data: data.field,
                success: function (ret) {
                    if (ret.code == 0) {
                        //关闭对话框
                        layer.closeAll();
                        //刷新表格数据
                        userTable.reload({});
                        layer.msg(ret.msg, {icon: 6});
                    } else {
                        layer.msg(ret.msg, {icon: 5});
                    }
                }
            })
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });

        //==================鼠标失焦判断用户名是否存在======================
        // $("#loginName").blur(function () {
        //     var node = this;
        //     let loginName = this.value;
        //     let loginInput = document.getElementById("loginName");
        //     console.log(loginName);
        //     $.ajax({
        //         type: "POST",
        //         url: "/user/checkLoginName",
        //         async: false, //改为同步请求
        //         data: {loginName: loginName},
        //         dataType: 'json',
        //         success: function (data) {
        //             console.log(data);
        //             if (data.code == 0) {
        //             } else {
        //                 node.focus();
        //                 loginInput.style = "border-color: red";
        //                 layer.msg('[' + loginName + ']'+data.msg, {icon: 5});
        //             }
        //         }
        //     });
        // });
    })
    ;
</script>

</html>